import logging
import math
from typing import Optional, List

from fastapi import APIRouter, Depends, Query, Path
from pydantic import Field, BaseModel
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from commons.BaseResponse import BaseResponse
from commons.PaginationBase import PaginationBase
from datebase import get_db
from utils.EncryptionUtil import oauth2_scheme, EncryptionMiddleware

task_point_router = APIRouter(prefix="/tsTaskpoint",tags=["课题组实验室资料管理"],dependencies=[Depends(oauth2_scheme)])

class ResearchGroupLabSearch(PaginationBase):
    """课题组实验室资料查询请求参数"""
    ftaskno: str = Field(..., description="任务编号")

@task_point_router.get("/list",summary="课题组实验室资料查询接口")
def list_task_point(search:ResearchGroupLabSearch = Query(),db: Session = Depends(get_db)):
    param = {}
    sql = "select ftaskno,a.fpointno,b.fpoint_name"
    sql = sql + " from m_ts_taskpoint a,a_ts_point b"
    sql = sql + " where 1=1"
    sql = sql + " and ftaskno = :ftaskno "
    sql = sql + " and a.fpointno=b.fpoint_no"
    sql = sql + " limit :limit offset :offset "
    param["ftaskno"] = search.ftaskno
    count = db.execute(text(sql), param).scalar()

    param = {}
    sql = "select ftaskno,a.fpointno,b.fpoint_name"
    sql = sql + " from m_ts_taskpoint a,a_ts_point b"
    sql = sql + " where 1=1"
    sql = sql + " and ftaskno = :ftaskno "
    sql = sql + " and a.fpointno=b.fpoint_no"
    sql = sql + " limit :limit offset :offset "
    param["ftaskno"] = search.ftaskno
    param["limit"] = search.limit
    param["offset"] = search.offset
    data = db.execute(text(sql), param).fetchall()

    data_list = []
    for key in range(len(data)):
        d1 = {}
        d1['ftaskno'] = data[key][0]
        d1['fpointno'] = data[key][1]
        d1['fpoint_name'] = data[key][2]
        data_list.append(d1)

    info_dict = {"list": data_list,
                 "limit": search.limit,
                 "page": search.pageIndex,
                 "pages": (count + search.limit - 1) // search.limit,
                 "total": count}
    return BaseResponse.success(data=info_dict)

@task_point_router.post("/delete/{taskno}/{pointno}",summary="课题组人员删除接口")
def delete_task_point(taskno:str=Path(description="课题组编号"),pointno:str=Path(description="站点编号"),db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "delete from m_ts_taskpoint where ftaskno= :taskno and fpointno= :pointno "
            db.execute(text(sql), {"taskno":taskno, "pointno":pointno})
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")

class ResearchGroupPersonCreate(BaseModel):
    """课题组人员新增请求参数"""
    ftaskno: str = Field(..., description="任务编号")
    fpointno: str = Field(..., description="点位编号")

@task_point_router.post("/create",summary="课题组人员新增接口")
def create_task_point(create:ResearchGroupPersonCreate,db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "select fpointno from m_ts_taskpoint where ftaskno= :ftaskno and fpointno= :fpointno "
            data = db.execute(text(sql),{
                "ftaskno":create.ftaskno,
                "fpointno":create.fpointno,
            }).fetchall()

            if len(data) > 0:
                return BaseResponse.error(message="课题组实验室已存在")
            else:
                sql = "insert into m_ts_taskpoint(ftaskno,fpointno)"
                sql = sql + " values( :ftaskno , :fpointno );"
                db.execute(text(sql), {
                    "ftaskno":create.ftaskno,
                    "fpointno":create.fpointno,
                })
                # 返回
                d1 = {}
                d1["ftaskno"] = create.ftaskno
                d1["fpointno"] = create.fpointno
                return BaseResponse.success(data=d1)
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")